#include "mutexqueue.h"

/**
 * @todo Ajouter les retours sur les erreurs.
 */
void initialize_MutexQueue(MutexQueue *mutexQueue, const int nbElementMax)
{
    mutexQueue->nbElementMax=nbElementMax;
    initialize_List(&(mutexQueue->fileSocket),create_IntList,delete_IntList, NULL, NULL);
    pthread_mutex_init(&(mutexQueue->mutexAcces), NULL);
    pthread_cond_init(&(mutexQueue->condVide), NULL);
}

void testament_MutexQueue(MutexQueue *mutexQueue)
{
    mutexQueue->nbElementMax=0;
    testament_List(&(mutexQueue->fileSocket));
    pthread_mutex_destroy(&(mutexQueue->mutexAcces));
    pthread_cond_destroy(&(mutexQueue->condVide));
}

MutexQueueReturn insert_MutexQueue(MutexQueue *mutexQueue, const Element element)
{
    pthread_mutex_lock(&(mutexQueue->mutexAcces));

    if(getSize_List(&(mutexQueue->fileSocket))==mutexQueue->nbElementMax)
    {
      pthread_mutex_unlock(&(mutexQueue->mutexAcces));
      return MUTEXQUEUE_MAX;
    }
    
    if(insertLast_List(&(mutexQueue->fileSocket), element) == LIST_ERR)
      {
	pthread_mutex_unlock(&(mutexQueue->mutexAcces));
	return MUTEXQUEUE_ERR;
      }
    pthread_cond_signal(&(mutexQueue->condVide));

    pthread_mutex_unlock(&(mutexQueue->mutexAcces));

    return MUTEXQUEUE_SUCCESS;

}

int getFirst_MutexQueue(MutexQueue *mutexQueue)
{
    int *s;
    int res;

    pthread_mutex_lock(&(mutexQueue->mutexAcces));

    while(getSize_List(&(mutexQueue->fileSocket))==0)
    {
      if(CONTINUE_SERVER)
        pthread_cond_wait(&(mutexQueue->condVide),&(mutexQueue->mutexAcces));
      else
	{
	  pthread_mutex_unlock(&(mutexQueue->mutexAcces));
	  return MUTEXQUEUE_END;
	}
    }

    s=getDataFirst_List(&(mutexQueue->fileSocket));
    res=(*s);
    
    deleteFirst_List(&(mutexQueue->fileSocket));

    pthread_mutex_unlock(&(mutexQueue->mutexAcces));

    return res;

}

void notifyEnd_MutexQueue(MutexQueue *mutexQueue)
{
  pthread_cond_broadcast(&(mutexQueue->condVide));
}
